import threading
import traceback

from drive import ADB, UiAutomator2

from tasks.taobao.common import CommonTaobao
from tasks.taobao.error import DealTaobaoError
from tasks.taobao.taobao import ChangeAccount, BuyProduct


class AutoTaoBaoShoppingFsm(threading.Thread, CommonTaobao):
    def __init__(self, android_ip):
        self.android_ip = android_ip
        self.adb = ADB(android_ip)
        self.ui_auto2 = UiAutomator2(android_ip)
        threading.Thread.__init__(self)
        CommonTaobao.__init__(self, android_ip)

    def change_account(self):
        try:
            ChangeAccount(self.android_ip).start()
        except Exception as e:
            raise Exception('{} change account failed, err={}'.format(self.android_ip, str(e)))

    def unlock_phone(self):
        self.adb.adb_connect()
        if not self.ui_auto2.check_screen_is_on():
            self.log_msg('即将点亮屏幕')
            self.ui_auto2.ui_auto2_unlock_screen()

    def buy(self):
        try:
            BuyProduct(self.android_ip).start()
        except Exception as e:
            print(traceback.format_exc())
            raise Exception('{} buy failed, err={}'.format(self.android_ip, str(e)))

    def run(self):
        self.log_msg('run task')
        try:
            self.unlock_phone()
            self.change_account()
            self.buy()
        except Exception as e:
            self.log_msg('run failed, err={}'.format(str(e)), err_flag=True)
            DealTaobaoError(self.android_ip).run()
        else:
            self.log_msg('all success')
